<?php

namespace app\controller;

use app\ApiController;
use app\util\Binance;
use app\util\LocalRpc;

class Index extends ApiController
{
    public function index()
    {
        return '<style type="text/css">*{ padding: 0; margin: 0; } div{ padding: 4px 48px;} a{color:#2E5CD5;cursor: pointer;text-decoration: none} a:hover{text-decoration:underline; } body{ background: #fff; font-family: "Century Gothic","Microsoft yahei"; color: #333;font-size:18px;} h1{ font-size: 100px; font-weight: normal; margin-bottom: 12px; } p{ line-height: 1.6em; font-size: 42px }</style><div style="padding: 24px 48px;"> <h1>:) </h1><p> ThinkPHP V' . \think\facade\App::version() . '<br/><span style="font-size:30px;">14载初心不改 - 你值得信赖的PHP框架</span></p><span style="font-size:25px;">[ V6.0 版本由 <a href="https://www.yisu.com/" target="yisu">亿速云</a> 独家赞助发布 ]</span></div><script type="text/javascript" src="https://tajs.qq.com/stats?sId=64890268" charset="UTF-8"></script><script type="text/javascript" src="https://e.topthink.com/Public/static/client.js"></script><think id="ee9b1aa918103c4fc"></think>';
    }

    public function hello($name = 'ThinkPHP6')
    {
        return 'hello,' . $name;
    }

    /**
     * 生成助记词
     */
    public function genMnemonicWord()
    {
        $Binance = new Binance();
        $data = $Binance->genMnemonicWord();
        $user = [];
        $user['wallet_eth_mnemonic'] = $data['mnemonic'];
        $user['wallet_eth_seed'] = $data['seed'];
        $user['wallet_eth_public_key'] = $data['public_key'];
        $user['wallet_eth_private_key'] = $data['private_key'];
        $user['wallet_eth_address'] = $data['address'];
        $this->jsuccess($user);
    }

    public function importMnemonicWord($mnemonic)
    {
        $Binance = new Binance();
        $data = $Binance->importByMnemonic($mnemonic);
        $user = [];
        $user['wallet_eth_mnemonic'] = $mnemonic;
        $user['wallet_eth_seed'] = $data['seed'];
        $user['wallet_eth_public_key'] = $data['public_key'];
        $user['wallet_eth_private_key'] = $data['private_key'];
        $user['wallet_eth_address'] = $data['address'];
        $this->jsuccess($user);
    }

    public function importPrivateKey($privatekey)
    {
        $Binance = new Binance();
        //init
        $user = [
            'wallet_eth_mnemonic' => '',
            'wallet_eth_seed' => '',
            'wallet_eth_public_key' => ''
        ];
        $user['wallet_eth_private_key'] = $privatekey;

        $res = $Binance->importByPrivatekey($privatekey, $err);
        if (!$res) {
            $this->jerror($err);
        }
        $user['wallet_eth_address'] = $res;
        $this->jsuccess($user);
    }

    public function importPublicKey($publickey)
    {
        $Binance = new Binance();
        $result = $Binance->importByPublicKey($publickey, $php_errormsg);
        if (!$result) {
            $this->jerror($php_errormsg);
        } else {
            $this->jsuccess($result);
        }
    }

    public function transfer($from, $to, $privatekey, $amount)
    {
        $LocalRpc = new LocalRpc();
        $result = $LocalRpc->transfer($from, $to, $privatekey, $amount, $err);
        if (!$result) {
            $this->jerror($err);
        } else {
            $this->jsuccess($result);
        }
    }

    public function balance($address)
    {
        $localRpc = new LocalRpc();
        $balanceBnb = $localRpc->balance($address);
//        $balanceLy = $localRpc->balance($address, "0xCf4f6a66972e7442f19C50250B0b24bc14Dc070E");
        $balanceLy = $localRpc->balance($address, "0x2f3C6D2FEa752942856F8e34AF26Ae76F4bBF53c");
        $return = [
            'bnb' => $balanceBnb,
            'ly' => $balanceLy
        ];
        $this->jsuccess($return);
    }

    public function balanceOf($address, $contract = "bnb")
    {
        $localRpc = new LocalRpc();
        $balanceLy = $localRpc->balanceOf($address, $contract);
        $this->jsuccess($balanceLy);
    }

    /**
     * 生成助记词
     */
    public function createWallet()
    {
        $Binance = new Binance();
        $data = $Binance->genMnemonicWord();
        $user = [];
        $user['wallet_eth_mnemonic'] = $data['mnemonic'];
        $user['wallet_eth_seed'] = $data['seed'];
//        $user['wallet_eth_public_key'] = $data['public_key'];
        $user['wallet_eth_private_key'] = $data['private_key'];
        $user['wallet_eth_address'] = $data['address'];
        $this->jsuccess($user);
    }

    private function validateAddress($address, $type = 'eth')
    {
        if ($type == 'eth') {
            /* PHP 代码段*/
            // ETH地址合法校验
            if (!(preg_match('/^(0x)?[0-9a-fA-F]{40}$/', $address))) {
                return false; //满足if代表地址不合法
            }
        } else {
            // BTC地址合法校验
            if (!(preg_match('/^(1|3)[a-zA-Z\d]{24,33}$/', $address) && preg_match('/^[^0OlI]{25,34}$/', $address))) {
                return false; //满足if代表地址不合法
            }
        }
        return true;
    }

    private $apiKey = "wC9iSt0h7QTnnBZTLArqhwQ1hJ0j3sZRlP2d15qeeBA";

    public function tokenInfo($contract)
    {
        if (!$this->validateAddress($contract)) {
            $this->jerror("error contract address");
        }
        $url = "https://api.dev.dex.guru/v1/chain/56/tokens/{$contract}?api-key={$this->apiKey}";
        $result = curl_get($url);
        $result = json_decode($result, true);
        if ($result['address'] == null) {
            $this->jerror("not found", 404);
        } else {
            $return = [
                'name' => $result['name'],
                'symbol' => $result['symbol'],
                'decimals' => $result['decimals'],
                'id' => $result['address'],
            ];
            $this->jsuccess($return);
        }
    }

    public function tokenPrice($contract = "bnb")
    {
        if ($contract == "bnb") {
            $contract = "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"; // default WBNB
        }
        if (!$this->validateAddress($contract)) {
            $this->jerror("error contract address");
        }

        $url = "https://api.dev.dex.guru/v1/chain/56/tokens/{$contract}/market?api-key={$this->apiKey}";
        $result = curl_get($url);
        $result = json_decode($result, true);
        $this->jsuccess($result['price_usd']);
    }

    public function transactions($address, $contract = null)
    {
        $bscscanKey = "V8Q9TD7WZG4BWU37NHYZG1EEZ9VNVCAJ9W";
        if ($contract != null) {
            $url = "https://api.bscscan.com/api?module=account&action=tokentx&contractaddress={$contract}&address={$address}&page=1&offset=500&startblock=0&endblock=999999999&sort=desc&apikey={$bscscanKey}";
        } else {
            $url = "https://api.bscscan.com/api?module=account&action=txlist&address={$address}&startblock=0&endblock=99999999&page=1&offset=500&sort=desc&apikey={$bscscanKey}";
        }


        $result = curl_get($url);
        $result = json_decode($result, true);
        if ($result['status'] == 1) {
            $this->jsuccess($result['result']);
        } else {
            $this->jerror($result['message']);
        }
    }

    public function transactionsBNB()
    {
        $url = "https://api.bscscan.com/api
               ?module=account
               &action=txlistinternal
               &startblock=0
               &endblock=2702578
               &page=1
               &offset=10
               &sort=asc
               &apikey=YourApiKeyToken";
    }

    /**
     * @param $from
     * @param $to
     * @param $privatekey
     * @param $amount
     * @param $contract
     * @param $withdrawId
     * @param $decimal
     * @return void
     */
    public function transferToken($from, $to, $privatekey, $amount, $contract, $withdrawId, $decimal = 18)
    {
        $LocalRpc = new LocalRpc();
        $result = $LocalRpc->transferToken($from, $to, $privatekey, $amount, $contract, $withdrawId, $decimal, $err);
        if (!$result) {
            $this->jerror($err);
        } else {
            $this->jsuccess(true);
        }
    }

    public function getGasFee()
    {
        $LocalRpc = new LocalRpc();
        $result = $LocalRpc->getGasFee($err);
        if (!$result) {
            $this->jerror($err);
        } else {
            $this->jsuccess($result);
        }
    }


}
